/*eslint-disable*/
    var zl =  {}
    zl.zlim = {
      iminstance: false, //聊天室对象
      auth_payload: null,
      isAnnounce: false, // 是否进行过公告
      announcementObj: {},
      initial: function(auth_payload, messagecb, eventcb) {
        if (!auth_payload) return
        this.auth_payload = auth_payload
        if (!auth_payload.use || auth_payload.use == 'jiguang') {
          this.iminstance = zl.jim
        } else if (auth_payload.use && auth_payload.use == 'tencent') {
          this.iminstance = zl.tim
        } else if (auth_payload.use && auth_payload.use == 'both') {
          try {
            var ratio = auth_payload.ratio ? auth_payload.ratio : '1:1'
            var arr = ratio.split(':')
            var random_num = Math.floor(Math.random() * 100 + 1)
            if (random_num % (parseInt(arr[0]) + parseInt(arr[1])) < arr[0]) {
              this.iminstance = zl.jim
  
              //组装极光auth_payload
              var jim_auth_payload = auth_payload.jiguang
              jim_auth_payload['nickname'] = auth_payload.nickname
              jim_auth_payload['headimgurl'] = auth_payload.headimgurl
              auth_payload = jim_auth_payload
            } else {
              this.iminstance = zl.tim
  
              //组装腾讯auth_payload
              var tim_auth_payload = auth_payload.tencent
              tim_auth_payload['nickname'] = auth_payload.nickname
              tim_auth_payload['headimgurl'] = auth_payload.headimgurl
              auth_payload = tim_auth_payload
            }
          } catch (e) {
            this.iminstance = zl.jim
  
            //组装极光auth_payload
            var jim_auth_payload = auth_payload.jiguang
            jim_auth_payload['nickname'] = auth_payload.nickname
            jim_auth_payload['headimgurl'] = auth_payload.headimgurl
            auth_payload = jim_auth_payload
          }
        }
        if (!this.iminstance) return
        let callback = e => {
          if (!this.isAnnounce) {
            this.getAnnouncement(e, eventcb)
            this.isAnnounce = true
          } else {
            eventcb(e)
          }
        }
        this.iminstance.initial &&
          this.iminstance.initial(auth_payload, messagecb, callback)
      },
  
      reconnect: function(ms) {
        if (!this.iminstance) return
        this.iminstance.reconnect && this.iminstance.reconnect(ms)
      },
  
      sendSingleMsg: function(content, callback, messageType) {
        if (!this.iminstance) return
        this.iminstance.sendSingleMsg &&
          this.iminstance.sendSingleMsg(content, callback, messageType)
      },
      // 进入页面拉去最新公告
      getAnnouncement: function(e, callback) {
        webim.getGroupInfo(
          {
            GroupIdList: [this.auth_payload.room_id],
            GroupBaseInfoFilter: ['Notification']
          },
          function(resp) {
            if (+resp.ErrorCode === 0) {
              var memberNum = resp.GroupInfo[0].Notification
              if (!memberNum) return
              let announcement = JSON.parse(memberNum).announcementContent
              typeof callback === 'function' && callback(e, announcement)
            }
          },
          function(err) {
          }
        )
      },
      exitRoom: function(callback) {
        if (!this.iminstance) {
          callback && callback()
          return
        }
        this.iminstance.exitRoom && this.iminstance.exitRoom(callback)
      }
    }
  
    zl.jim = {
      JIM: false, //IM消息对象
      auth_payload: false, //认证回调信息
      messagecb: false, //聊天室消息回调
      onlineCount: 0,
      messageMap: { maxLimit: 1000, map: {}, queue: [] },
      eventcb: false,
      isConnecting: false,
      initial: function(auth_payload, messagecb, eventcb) {
        if (!auth_payload) return
  
        this.auth_payload = auth_payload
        this.messagecb = messagecb
        this.eventcb = eventcb
        this.onlineCount = 0
        this.isConnecting = true
        this.messageMap = { maxLimit: 1000, map: {}, queue: [] }
  
        var _this = this
        _this.JIM = new JMessage({
          debug: false
        })
        _this.JIM._randonKey = new Date().getTime()
        _this.JIM.onDisconnect(function() {
          //100ms后自动重连
          _this.JIM.loginOut() //退出登录
          _this.eventcb && _this.eventcb('offline')
          _this.reconnect(100)
        }) //异常断线监听
  
        this.iminitial()
        setInterval(function() {
          if (!_this.isConnect()) {

            _this._JIM && _this._JIM.loginOut() //退出登录
            _this.reconnect()
          }
        }, 20 * 1000)
      },
  
      refreshSign: function() {
        var auth_payload = this.auth_payload
        var _this = this
        $.ajax({
          url: '/wxpub/api/chatsign?t=' + new Date().getTime(),
          type: 'GET',
          dataType: 'json',
          success: function(json) {
            if (json.errcode == '0') {
              var map = json.data
              for (var key in map) {
                auth_payload[key] = map[key]
              }
              _this.reconnect(10 * 1000)
            }
          }
        })
      },
      checkThisJIM: function(JIM) {
        var _JIM = this.JIM
        if (!_JIM || !_JIM._randonKey) return true
        if (!JIM || !JIM._randonKey) return true
  
        if (_JIM._randonKey == JIM._randonKey) {
          return true
        }
        return false
      },
      iminitial: function() {
        var _JIM = this.JIM
        var messagecb = this.messagecb
        var auth_payload = this.auth_payload
        var _this = this
  
        var initTimer = null
        initTimer = setTimeout(function() {
          _this.isConnecting = false
          initTimer = null
          _this.reconnect()
        }, 10 * 1000)
        var clearCb = function() {
          _this.isConnecting = false
          if (initTimer) {
            clearTimeout(initTimer)
            initTimer = null
          }
        }
        try {
          _JIM
            .init({
              appkey: auth_payload.appkey,
              random_str: auth_payload.random_str,
              signature: auth_payload.signature,
              timestamp: auth_payload.timestamp,
              flag: auth_payload.flag || 1
            })
            .onSuccess(function(data) {
              clearCb()
              _this.doLogin(_JIM)
            })
            .onFail(function(data) {
              clearCb()
              if (!data || !data.code) return
              //880102 signatu fail;880106:signatu is expire
              if (data.code == 880102 || data.code == 880106) {
                //重新刷新签名
                _this.refreshSign()
              }
            })
            .onTimeout(function(data) {
              clearCb()
            }) //异常断线监听
        } catch (e) {
          //当前网络断开情况下，异常崩溃	捕获
          clearCb()
          _this.reconnect(10 * 1000)
        }
      },
      isMessageExist: function(msg_id) {
        if (!msg_id) return false
        return this.messageMap.map[msg_id] ? true : false
      },
      messageQueue: function(msg_id) {
        if (!msg_id || this.isMessageExist(msg_id)) return
        if (this.messageMap.queue.length >= this.messageMap.maxLimit) {
          var first_id = this.messageMap.queue.shift()
          if (this.messageMap.map[first_id]) {
            delete this.messageMap.map[first_id]
          }
        }
        this.messageMap.queue.push(msg_id)
        this.messageMap.map[msg_id] = 1
      },
      doLogin: function(_JIM) {
        var messagecb = this.messagecb
        var auth_payload = this.auth_payload
        var eventcb = this.eventcb
        var _this = this
        try {
          //用户登录
          _JIM
            .login({
              username: auth_payload.username,
              password: auth_payload.password
            })
            .onSuccess(function(data) {
              _this.onLoginIn(_JIM)
            })
            .onFail(function(data) {
              if (data && data.code == 880103) {
                //用户不存在
                _JIM
                  .register({
                    //注册用户
                    username: auth_payload.username,
                    password: auth_payload.password,
                    nickname: auth_payload.nickname
                      ? auth_payload.nickname
                      : '之了考友'
                  })
                  .onSuccess(function(data) {
                    _this.doLogin(_JIM)
                  })
                  .onFail(function(data) {})
              } else {
              }
            })
        } catch (e) {
          //当前网络断开情况下，异常崩溃	捕获
          _this.reconnect()
        }
      },
      reconnect: function(delay) {
        delay = delay ? delay : 3 * 1000
        var _this = this
        if (this.isConnecting) return
  
        this.isConnecting = true
        setTimeout(function() {
          _this.iminitial()
        }, delay)
      },
      isConnect: function() {
        //用户是否登录
        var _JIM = this.JIM
        if (!_JIM) return false
        return _JIM.isConnect()
      },
      onLoginIn: function(_JIM) {
        //登录成功后进入聊天室以及监听聊天室消息
        var messagecb = this.messagecb
        var auth_payload = this.auth_payload
        var eventcb = this.eventcb
        var _this = this
        if (!_JIM) return
  
        /*第一次不显示上线，第二次以后每次上线提醒用户*/
        if (this.onlineCount > 1) {
          eventcb && eventcb('online') //第N次上线
        } else {
          eventcb && eventcb('login') //第一次登陆成功
        }
        try {
          //登录后进入聊天室
          _JIM
            .enterChatroom({ id: auth_payload.room_id })
            .onSuccess(function(data) {})
            .onFail(function(data) {
            })
        } catch (e) {
          _this.reconnect()
        }
        //聊天室消息回调
        _JIM.onRoomMsg(function(data) {
          //只接收同一房间号的消息
          if (data && data.room_id == auth_payload.room_id) {
            if (!_this.isMessageExist(data.msg_id)) {
              messagecb && messagecb(data)
              _this.messageQueue(data.msg_id)
            }
          }
        })
        _JIM.onEventNotification(function(data) {
          if (data.event_type == 1 && data.extra == 0) {
            // _this.eventcb('another_login');
          }
        })
      },
      sendSingleMsg: function(content, callback) {
        //发送聊天室信息，某个用户发送了通过callback进行回调获取该用户自己发的
        var _JIM = this.JIM
        var auth_payload = this.auth_payload
        var messagecb = this.messagecb
        var eventcb = this.eventcb
        var _this = this
        if (!_JIM) return
        if (!this.isConnect()) {
          eventcb && eventcb('reconnect')
          this.reconnect(100)
          return
        }
        if (!_JIM.isLogin()) {
          eventcb && eventcb('leave')
          this.reconnect(100)
          callback && callback(null, null)
          return
        }
        var sendTimer = setTimeout(function() {
          eventcb && eventcb('timeout')
          callback && callback(null, null)
          sendTimer = null
        }, 5 * 1000)
        _JIM
          .sendChatroomMsg({
            target_rid: auth_payload.room_id,
            content: content
          })
          .onSuccess(function(data, msg) {
            callback && callback(data, msg)
            if (!_this.isMessageExist(msg.msg_id)) {
              _this.messageQueue(msg.msg_id)
            }
            if (sendTimer) {
              clearTimeout(sendTimer)
              sendTimer = null
            }
          })
          .onFail(function(data) {
            if (data.code == '881502') {
              eventcb && eventcb('ban')
            } else {
              eventcb && eventcb('fail')
            }
            callback && callback(data, null)
            if (sendTimer) {
              clearTimeout(sendTimer)
              sendTimer = null
            }
          })
          .onTimeout(function(data) {
            //触发消息发送超时事件
            if (!sendTimer) return
            eventcb && eventcb('timeout')
            callback && callback(null, null)
            clearTimeout(sendTimer)
            sendTimer = null
          })
      },
      exitRoom: function(callback) {
        //退出聊天室并且退出登录
        var _JIM = this.JIM
        var auth_payload = this.auth_payload
  
        if (!_JIM || !auth_payload) {
          callback && callback()
          return
        }
        var callCount = 0
        var localCallback = function() {
          if (callCount) return
          callCount++
          _JIM.loginOut() //退出登录
          callback && callback()
        }
        setTimeout(function() {
          //防止其他异常未处理事件
          localCallback()
        }, 500)
        localCallback()
        //退出房间
      }
    }
  
    zl.tim = {
      auth_payload: false, //认证回调信息
      messagecb: false, //聊天室消息回调
      eventcb: false,
  
      loginInfo: {},
      listeners: {},
      options: {},
  
      selType: null, //当前聊天类型-群聊
      selToID: null, //当前选中聊天id（当聊天类型为私聊时，该值为好友帐号，否则为群号）
      selSess: null, //当前聊天会话对象
  
      initial: function(auth_payload, messagecb, eventcb) {
        if (!auth_payload) return
        this.auth_payload = auth_payload
        this.messagecb = messagecb
        this.eventcb = eventcb
  
        this.iminitial()
      },
  
      iminitial: function() {
        var messagecb = this.messagecb
        var auth_payload = this.auth_payload
  
        this.selType = webim.SESSION_TYPE.GROUP
        this.selToID = auth_payload.room_id
  
        //当前用户身份
        this.loginInfo = {
          sdkAppID: auth_payload.sdkAppID, //用户所属应用id,必填
          accountType: auth_payload.accountType, //用户所属应用帐号类型，必填
          identifier: auth_payload.identifier, //当前用户ID,必须是否字符串类型，必填
          userSig: auth_payload.userSig, //当前用户身份凭证，必须是字符串类型，必填
          identifierNick: auth_payload.nickname //当前用户昵称，不用填写，登录接口会返回用户的昵称，如果没有设置，则返回用户的id
          //'headurl': 'img/me.jpg' //当前用户默认头像，选填，如果设置过头像，则可以通过拉取个人资料接口来得到头像信息
        }
  
        //监听事件
        this.listeners = {
          onConnNotify: this.onConnNotify, //监听连接状态回调变化事件,必填
          jsonpCallback: this.jsonpCallback, //IE9(含)以下浏览器用到的jsonp回调函数，
          onMsgNotify: this.onMsgNotify, //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
          onBigGroupMsgNotify: this.onBigGroupMsgNotify, //监听新消息(直播聊天室)事件，直播场景下必填
          onKickedEventCall: this.onKickedEventCall //被其他登录实例踢下线
        }
  
        //初始化时，其他对象，选填
        this.options = {
          isAccessFormalEnv: true, //是否访问正式环境，默认访问正式，选填
          isLogOn: false //是否开启控制台打印日志,默认开启，选填
        }
  
        this.doLogin()
      },
  
      doLogin: function() {
        var messagecb = this.messagecb
        var auth_payload = this.auth_payload
        var eventcb = this.eventcb
        var _this = this
  
        webim.login(
          this.loginInfo,
          this.listeners,
          this.options,
          function(resp) {
            if (resp.identifierNick != auth_payload.nickname) {
              //设置用户昵称
              webim.setProfilePortrait(
                {
                  ProfileItem: [
                    {
                      Tag: 'Tag_Profile_IM_Nick',
                      Value: auth_payload.nickname
                    }
                  ]
                },
                function(resp2) {},
                function(err2) {}
              )
            }
            _this.onLoginIn()
          },
          function(err) {}
        )
      },
  
      onLoginIn: function() {
        //登录成功后进入聊天室以及监听聊天室消息
        var messagecb = this.messagecb
        var auth_payload = this.auth_payload
        var eventcb = this.eventcb
        var _this = this
  
        eventcb && eventcb('login') //第一次登陆成功
  
        //加入聊天室
        webim.applyJoinBigGroup(
          {
            GroupId: auth_payload.room_id
          },
          function(resp) {
            if (resp.JoinedStatus && resp.JoinedStatus == 'JoinedSuccess') {
              eventcb && eventcb('online')
            }
          },
          function(err) {}
        )
      },
  
      sendSingleMsg: function(content, callback, messageType) {
        //发送聊天室信息，某个用户发送了通过callback进行回调获取该用户自己发的
        var auth_payload = this.auth_payload
        var messagecb = this.messagecb
        var eventcb = this.eventcb
        var _this = this
  
        var msgContent = content
        if (!this.selSess) {
          this.selSess = new webim.Session(this.selType, this.selToID)
        }
        var isSend = true //是否为自己发送
        var seq = -1 //消息序列，-1表示sdk自动生成，用于去重
        var random = Math.round(Math.random() * 4294967296) //消息随机数，用于去重
        var msgTime = Math.round(new Date().getTime() / 1000) //消息时间戳
        var subType = webim.GROUP_MSG_SUB_TYPE.COMMON //消息子类型-普通消息
  
        var msg = new webim.Msg(
          this.selSess,
          isSend,
          seq,
          random,
          msgTime,
          this.loginInfo.identifier,
          subType,
          this.loginInfo.identifierNick
        )
  
        var text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex
        //解析文本和表情
        var expr = /\[[^[\]]{1,3}\]/gm
        var emotions = msgContent.match(expr)
        if (!emotions || emotions.length < 1) {
          if (+messageType === 0) {
            text_obj = new webim.Msg.Elem.Text(msgContent)
            msg.addText(text_obj)
          } else {
            // 发送自定义消息
            text_obj = new webim.Msg.Elem.Custom(msgContent, '', '自定义消息')
            msg.addCustom(text_obj)
          }
        } else {
          for (var i = 0; i < emotions.length; i++) {
            tmsg = msgContent.substring(0, msgContent.indexOf(emotions[i]))
            if (tmsg) {
              text_obj = new webim.Msg.Elem.Text(tmsg)
              msg.addText(text_obj)
            }
            emotionIndex = webim.EmotionDataIndexs[emotions[i]]
            emotion = webim.Emotions[emotionIndex]
  
            if (emotion) {
              face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i])
              msg.addFace(face_obj)
            } else {
              text_obj = new webim.Msg.Elem.Text(emotions[i])
              msg.addText(text_obj)
            }
            restMsgIndex = msgContent.indexOf(emotions[i]) + emotions[i].length
            msgContent = msgContent.substring(restMsgIndex)
          }
          if (msgContent) {
            text_obj = new webim.Msg.Elem.Text(msgContent)
            msg.addText(text_obj)
          }
        }
  
        var sendTimer = setTimeout(function() {
          eventcb && eventcb('timeout')
          callback && callback(null, null)
          clearTimeout(sendTimer)
          sendTimer = null
        }, 5 * 1000)
        webim.sendMsg(
          msg,
          function(resp) {
            callback && callback(null, true)
            if (sendTimer) {
              clearTimeout(sendTimer)
              sendTimer = null
            }
          },
          function(err) {
            if (err.ErrorCode == 10017) {
              eventcb && eventcb('ban')
            } else {
              eventcb && eventcb('fail')
            }
            callback && callback(null, null)
            if (sendTimer) {
              clearTimeout(sendTimer)
              sendTimer = null
            }
          }
        )
      },
  
      onConnNotify: function(resp) {
        var eventcb = zl.tim.eventcb
        var info
        switch (resp.ErrorCode) {
          case webim.CONNECTION_STATUS.ON:
            webim.Log.warn('建立连接成功: ' + resp.ErrorInfo)
            break
          case webim.CONNECTION_STATUS.OFF:
            eventcb && eventcb('network')
            info =
              '连接已断开，无法收到新消息，请检查下你的网络是否正常: ' +
              resp.ErrorInfo
            webim.Log.warn(info)
            break
          case webim.CONNECTION_STATUS.RECONNECT:
            info = '连接状态恢复正常: ' + resp.ErrorInfo
            webim.Log.warn(info)
            break
          default:
            webim.Log.error('未知连接状态: =' + resp.ErrorInfo)
            break
        }
      },
  
      //监听新消息(私聊(包括普通消息、全员推送消息)，普通群(非直播聊天室)消息)事件
      //newMsgList 为新消息数组，结构为 [Msg]
      onMsgNotify: function(newMsgList) {
        //暂不处理
      },
  
      //监听直播聊天室新消息事件
      //newMsgList 为新消息数组，结构为[Msg]
      //监听大群新消息（普通，点赞，提示，红包）
      onBigGroupMsgNotify: function(newMsgList) {
        var messagecb = zl.tim.messagecb
        for (var i = newMsgList.length - 1; i >= 0; i--) {
          //遍历消息，按照时间从后往前
          var msg = newMsgList[i]
          var isSelfSend, fromAccount, fromAccountNick, sessType, subType
  
          isSelfSend = msg.getIsSend() //消息是否为自己发的
          if (isSelfSend) {
            continue
          }
          fromAccount = msg.getFromAccount()
          if (!fromAccount) {
            fromAccount = ''
          }
          fromAccountNick = msg.getFromAccountNick()
          if (!fromAccountNick) {
            fromAccountNick = '之了考友'
          }
          sessType = msg.getSession().type()
          subType = msg.getSubType()
  
          var msgContent = ''
          if (subType == webim.GROUP_MSG_SUB_TYPE.COMMON) {
            var elems, elem, type, content
            elems = msg.getElems() //获取消息包含的元素数组
            for (var j in elems) {
              elem = elems[j]
              type = elem.getType() //获取元素类型
              content = elem.getContent() //获取元素对象
              switch (type) {
                case webim.MSG_ELEMENT_TYPE.TEXT:
                  msgContent = content.getText()
                  break
                // 获取自定义消息（商品弹窗）
                case webim.MSG_ELEMENT_TYPE.CUSTOM:
                  msgContent = JSON.parse(content.data)
                  break
                default:
                  break
              }
            }
          }
          // 接受公告消息
          if (+subType === 2) {
            let announcementList = msg.getElems()[0].content.groupInfoList
            if (announcementList.length > 0) {
              msgContent = JSON.parse(announcementList[0].value)
            }
          }
          if (msgContent) {
            var data = {
              //封装成极光格式
              content: {
                from_id: fromAccount,
                from_name: fromAccountNick,
                msg_body: {
                  text: msgContent
                }
              }
            }
            messagecb && messagecb(data)
          }
        }
      },
  
      onKickedEventCall: function() {
        //异地登录，微信不处理
      },
  
      jsonpCallback: function(rspData) {
        webim.setJsonpLastRspData(rspData)
      },
  
      exitRoom: function(callback) {
        //退出登录
        var auth_payload = this.auth_payload
        if (!auth_payload) {
          callback && callback()
          return
        }
        var callCount = 0
        var localCallback = function() {
          if (callCount) return
          callCount++
          webim.logout(
            //退出登录
            function(resp) {}
          )
          callback && callback()
        }
        setTimeout(function() {
          //防止其他异常未处理事件
          localCallback()
        }, 500)
        localCallback()
      }
    }
  
    export default zl
  